package chrisbode.cps142.a2;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class MovieRoster {
	private ArrayList<MovieTicket> movies;

	public MovieRoster() {
		movies = new ArrayList<MovieTicket>();
	}

	public MovieRoster(File f) throws IOException {
		this();
		this.load(f);
	}

	public void load(File file) throws IOException {
		this.load(new FileInputStream(file));
	}

	public void load(InputStream is) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));

		String nextLine;

		while ((nextLine = reader.readLine()) != null) {
			nextLine = nextLine.trim();

			if (nextLine.length() > 0 && nextLine.charAt(0) != '#') {
				String[] args = nextLine.split("\\|", 4);

				try {
					String title, type;
					int totalSeats, soldSeats;

					title = args[0];
					type = args[1];

					totalSeats = Integer.parseInt(args[2]);
					soldSeats = Integer.parseInt(args[3]);

					if (type.equals("3D")) {
						movies.add(new Ticket3D(title, totalSeats, soldSeats));
					} else if (type.equals("2D")) {
						movies.add(new Ticket2D(title, totalSeats, soldSeats));
					} else {
						movies.add(new TicketOld(title, totalSeats, soldSeats));
					}
				} catch (Exception e) {
					System.err
							.println("Invalid Movie Entry (" + nextLine + ")");
				}
			}
		}
	}

	public void listMovies() {
		for (int i = 0; i < this.movies.size(); i++) {
			System.out.println((i) + ":\t" + this.movies.get(i));
		}
	}

	public double sell(int movieIndex, Patron patron) throws TheatreCapacityException {
		MovieTicket ticket = this.movies.get(movieIndex);
		ticket.incrementSoldSeats();
		return ticket.getPrice(patron);
	}
}
